// Ionic Starter App

// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
angular.module('starter', ['ionic'])

.run(function($ionicPlatform) {
    $ionicPlatform.ready(function() {
      if (window.cordova && window.cordova.plugins.Keyboard) {
        // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
        // for form inputs)
        cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);

        // Don't remove this line unless you know what you are doing. It stops the viewport
        // from snapping when text inputs are focused. Ionic handles this internally for
        // a much nicer keyboard experience.
        cordova.plugins.Keyboard.disableScroll(true);
      }
      if (window.StatusBar) {
        StatusBar.styleDefault();
      }
    });
  })
  .controller("YdzCtrl", ["$scope",
    "$ionicModal",
    "YdzBase",
    "localStorage",
    function($scope, $ionicModal, $ydz_base, $local_storage) {
      // 登陆
      $ionicModal.fromTemplateUrl("template/login_modal.html", {
        scope: $scope
      }).then(function(modal) {
        $scope.modal = modal;
        $scope.modal.show();
        $scope.login = {
          Status: "检查登陆状态",
          Name: "",
          Waiting: true,
          PassWd: ""
        };
      });
      // 点击登陆：
      $scope.loginApp = function() {
        $scope.login.Status = "检查登陆信息";
        $scope.login.Waiting = true;
        var name = $scope.login.Name,
          orig_passwd = $scope.login.PassWd,
          passwd = CryptoJS.MD5(orig_passwd).toString(CryptoJS.enc.Hex);
        var tid = setInterval(function() {
          if ($scope.salerList && $scope.salerList.length > 0) {
            for (var i = 0; i < $scope.salerList.length; i++) {
              var saler = $scope.salerList[i];
              if (saler.LoginName = name &&
                saler.Passwd == passwd) {

                $scope.login.Waiting = false;
                $scope.login.Status = "登陆成功！";
                $scope.modal.hide();
                clearInterval(tid);
                $local_storage.set("loginInfo", {
                  name: name,
                  passwd: orig_passwd,
                  create_time: (!!$scope.login.CreateTime ?
                    $scope.login.CreateTime :
                    (new Date()).getTime())
                })
                getAllBaseInfo();
                $scope.$apply();
                return
              }
            }
            $scope.login.Status = "请使用易定制员工账户密码登陆";
            $scope.login.Waiting = false;
            $scope.$apply();
          }
        }, 0)
      }
      $local_storage.get("loginInfo", function(info) {
          if (info !== "") {
            var name = info.name,
              passwd = info.passwd,
              create_time = parseInt(info.create_time);
            if (Number.isFinite(create_time)) {
              var day_dur = ((new Date()).getTime() - create_time) /
                1000 / 3600 / 24;
              if (day_dur <= 7) {
                $scope.login.Name = name;
                $scope.login.PassWd = passwd;
                $scope.login.CreateTime = create_time;
                $scope.login.Status = "检测到之前账号，自动登陆 ....";
                $scope.loginApp();
                return
              }
            }
          }
          $scope.login.Status = "请使用易定制员工账户密码登陆";
          $scope.login.Waiting = false;
        })
        // 主动登陆
      $scope.showModal = function() {
        $scope.modal.show();
        $scope.login.Status = "请使用易定制员工账户密码登陆";
        $scope.login.Waiting = false;
      }
      $ydz_base.getCities(function(cities) {
          $scope.CityList = cities;
          $local_storage.get("city", function(city) {
            $scope.customer.City = (city == "" ? cities[0] :
              city);
            $scope.$apply();
          });
        })
        // ion-item 和 .item 都会声明一个子scope，
        // 所以，要么在每个属性前加$parent，要么把属性都统一放到
        // 一个obj内部，子scope会继承这些obj属性，但是不会继承
        // 基本类型(int, string etc.)的属性。
      $scope.customer = {};
      $scope.employee = {};
      $scope.Orders = [];
      $scope
        .showDelete = false;
      $scope.TotalSum = 0;
      // $scope.$watch("City") 无法使用。必须使用ng-change，
      // 或者把City包装到一个obj中。
      $scope.$watch("customer.City", changeCity);
      $scope.FabricChanged =
        function(idx) {
          var order = $scope.Orders[idx],
            fabricBrand = order.FabricBrand;
          order.FabricBookList = $scope.fabricBookMap[fabricBrand];
          order.FabricBook = order.FabricBookList[0];
          $scope.FabricBookChanged(idx);
        }
      $scope.FabricBookChanged = function(idx) {
        var order = $scope.Orders[idx],
          key = order.FabricBrand + ":" + order.FabricBook;
        order.FabricRangeList = $scope.fabricRangeMap[key];
        order.FabricRange = order.FabricRangeList[0];
      }
      $scope.switchDelete = function() {
        $scope.showDelete = !$scope.showDelete;
      }
      $scope.addOrder = (function() {
        // 防止重复点击
        var active = false;
        return function() {
          if (!active) {
            active = true;
            $scope.Orders.push({
              SuitType: "西服",
              FabricBrand: "LESS&MORE",
              FabricNumber: "",
              Price: 0,
              Count: 1,
              Discount: 10,
              PayMinus: 0,
              _total: 0,
            });
            $scope.FabricChanged($scope.Orders.length - 1);
            setTimeout(function() {
              active = false;
            }, 1000)
          }
        }
      })();

      $scope.delOrder = function(i) {
        var o = $scope.Orders.splice(i, 1);
        $scope.TotalSum -= o[0]._total;
        o = null;
        $scope.$broadcast("item_updated");
      }
      $scope.payOrders = function(tp) {
        var orders = {
          CustomerName: $scope.customer.Name,
          CustomerTel: $scope.customer.Tel,
          CustomerAddr: $scope.customer.Addr,
          ShopCity: $scope.customer.City,
          SalerName: $scope.employee.Saler.LoginName,
          TailorName: $scope.employee.Tailor.LoginName,
          UserProfile: $scope.customer.Note,
          Orders: [],
        };
        if (window.cordova && window.cordova.plugins.LakalaPay) {
          var LakalaPay = window.cordova.plugins.LakalaPay;

          angular.forEach($scope.Orders, function(o) {
            orders.Orders.push({
              SuitType: o.SuitType,
              FabricBrand: o.FabricBrand,
              FabricBook: o.FabricBook,
              FabricRange: o.FabricRange,
              FabricNumber: o.FabricNumber,
              FabricPricePerMeter: o.FabricPricePerMeter,
              Price: o.Price,
              Count: o.Count,
              Discount: o.Discount,
            })
          })
          LakalaPay.payOrders([orders, $scope.TotalSum, tp]);
        }
      }
      $scope.printOrders = function() {
        // TODO 打印可以需要cordova的系统接口
        console.log("print all order!")
      }
      $scope.$on("total_sum_update", function(e, diff) {
        $scope.TotalSum += diff;
        $scope.TotalSum = Math.floor($scope.TotalSum * 100) / 100;
      })


      function changeCity(new_city) {
        if (!!new_city) {
          $local_storage.set("city", new_city);
          $ydz_base.getEmployee("tailor", new_city, function(tailors) {
            $scope.tailorList = tailors;
            $scope.Tailor = tailors[0];
          })
          $ydz_base.getEmployee("saler", new_city, function(salers) {
            $scope.salerList = salers;
            $scope.Saler = salers[0];
          })
        }
      }

      // 登陆成功后去请求数据
      function getAllBaseInfo() {
        $ydz_base.getProductsList(function(products_list) {
          $scope.ProductsList = products_list;
        })
        $ydz_base.getFabricList(function(fabric_list) {
          $scope.FabricList = fabric_list;
        })
        $ydz_base.getPriceAlgo(function(algo) {
          $scope._compute_price = {};
          angular.forEach(algo, function(func, suit) {
            $scope._compute_price[suit] = new Function(
              "p",
              func);
          })
        })
        $ydz_base.getFabricPrice(function(fabric_price) {
          $scope.AllFabricPrice = fabric_price;
          var fabric_supplier_map = {},
            fabric_book_map = {},
            fabric_price_map = {},
            fabric_range_map = {};
          angular.forEach(fabric_price, function(item) {
            var key = item.FabricBrand + ":" + item.FabricBook,
              key2 = key + ":" + item.FabricRange;
            if (!fabric_book_map[item.FabricBrand]) {
              fabric_book_map[item.FabricBrand] = {};
            }
            if (!fabric_range_map[key]) {
              fabric_range_map[key] = {};
            }
            fabric_supplier_map[key2] = item.FabricSupplier;
            fabric_range_map[key][item.FabricRange] = 1;
            fabric_price_map[key2] = [item.SuitPrice,
              item
              .PricePerMeter
            ];
            fabric_book_map[item.FabricBrand][item.FabricBook] =
              1;
          })
          angular.forEach(fabric_book_map, function(item,
            key) {
            var book_list = [];
            for (var b in item) {
              book_list.push(b);
            }
            fabric_book_map[key] = book_list;
          })
          angular.forEach(fabric_range_map, function(item,
            key) {
            var range_list = [];
            for (var r in item) {
              range_list.push(r)
            }
            fabric_range_map[key] = range_list;
          })
          $scope.fabricBookMap = fabric_book_map;
          $scope.fabricSupplierMap = fabric_supplier_map;
          $scope.fabricPriceMap = fabric_price_map;
          $scope.fabricRangeMap = fabric_range_map;
        })
      }
    }

  ])
  .directive("oneOrder", function() {
    return {
      restrict: "A",
      link: function($scope, elem, attr) {
        var oid = parseInt(attr.orderId);
        $scope._order = $scope.Orders[oid];
        $scope.$on("item_updated", function() {
          if ($scope.Orders.length > oid) {
            $scope._order = $scope.Orders[oid];
          } else {
            setTimeout(function() {
              $scope.$destroy();
            }, 1000)
          }
        })
        $scope.$watchGroup([
          "_order.SuitType",
          "_order.FabricBrand",
          "_order.FabricBook",
          "_order.FabricRange",
          "_order.Count",
          "_order.Discount",
          "_order.PayMinus"
        ], function(new_v, old_v) {
          var suitType = new_v[0],
            fabricBrand = new_v[1],
            fabricBook = new_v[2],
            fabricRange = new_v[3],
            count = parseFloat(new_v[4]),
            discount = parseFloat(new_v[5]),
            payMinus = parseFloat(new_v[6]);
          if (Number.isFinite(count) &&
            Number.isFinite(discount) &&
            Number.isFinite(payMinus)) {
            var key = fabricBrand + ":" + fabricBook,
              key2 = key + ":" + fabricRange,
              price_info = $scope.fabricPriceMap[key2];
            if (discount > 10) {
              $scope._order.Discount = discount / 10;
              discount /= 10;
            }
            if (!!price_info && price_info.length > 1) {
              var base_price = price_info[0],
                func = $scope._compute_price[suitType];
              // 精确到小数点后2位
              var price = round2p((
                angular.isFunction(func) ?
                func(base_price) :
                $scope._compute_price.default(base_price)
              ) - payMinus / count / discount * 10);
              var total = round2p(price * count * discount / 10);
              if (total <= 0) {
                alert("价格已经小于0！");
              }
              // price是单品的价格
              // total是 单品价格*数量*折扣-惠减
              if ($scope._order.Price !== price ||
                $scope._order._total != total) {
                $scope.$emit("total_sum_update",
                  total - $scope._order._total);
                $scope._order.Price = price;
                $scope._order._total = total;
              }
              $scope._order.FabricPricePerMeter = price_info[1];
            } else {
              console.log("price for `%s` not found", key2);
            }
          } else {
            console.error(
              "invalid order Count[%O] or Discount[%O] or PayMinus[%O]",
              count, discount, payMinus)
          }
        })

        function round2p(f) {
          return Math.floor(f * 100) / 100;
        }
      }
    }
  })
